// 后台脚本 - 管理扩展状态
chrome.runtime.onInstalled.addListener(() => {
  // 初始化默认数据
  chrome.storage.local.get(['groups', 'keywords', 'settings', 'filters'], result => {
    const defaultData = {
      groups: result.groups || [
        {
          id: 'default-group',
          name: '默认分组',
          color: '#4285f4',
          createdAt: new Date().toISOString()
        }
      ],
      keywords: result.keywords || [],
      settings: result.settings || {
        enabled: true,
        scanDelay: 300,
        regexSupport: false,
        tooltipTheme: 'dark',
        tooltipPosition: 'follow'
      },
      filters: result.filters || {
        group: '',
        search: '',
        sort: 'name'
      }
    };

    chrome.storage.local.set(defaultData);
  });
});

// 检查 chrome.commands 是否存在，避免在不支持的环境下报错
if (chrome.commands) {
  // 添加快捷键支持
  chrome.commands.onCommand.addListener((command) => {
    if (command === 'toggle-highlight') {
      chrome.storage.local.get(['settings'], (result) => {
        const newSettings = {
          ...result.settings,
          enabled: !result.settings.enabled
        };

        chrome.storage.local.set({ settings: newSettings }, () => {
          // 通知所有标签页更新高亮状态
          chrome.tabs.query({}, (tabs) => {
            tabs.forEach((tab) => {
              // 只向有 content script 的标签页发送消息
              if (tab.url && tab.url.startsWith('http')) {
                chrome.tabs.sendMessage(tab.id, {
                  action: 'updateHighlight',
                  settings: newSettings
                }).catch(() => {
                  // 忽略发送消息失败的情况（比如页面没有 content script）
                });
              }
            });
          });

          // 更新扩展图标状态
          updateExtensionIcon(newSettings.enabled);
        });
      });
    }
  });
}

// 更新扩展图标状态
function updateExtensionIcon(enabled) {
  const iconPath = enabled ? {
    "16": "icons/icon16.png",
    "32": "icons/icon32.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  } : {
    "16": "icons/icon-disabled16.png",
    "32": "icons/icon-disabled32.png",
    "48": "icons/icon-disabled48.png",
    "128": "icons/icon-disabled128.png"
  };

  chrome.action.setIcon({ path: iconPath });
}

// 监听存储变化，更新图标状态
chrome.storage.onChanged.addListener((changes, namespace) => {
  if (namespace === 'local' && changes.settings) {
    const enabled = changes.settings.newValue.enabled;
    updateExtensionIcon(enabled);
  }
});

// 扩展启动时设置正确的图标
chrome.runtime.onStartup.addListener(() => {
  chrome.storage.local.get(['settings'], (result) => {
    const enabled = result.settings?.enabled ?? true;
    updateExtensionIcon(enabled);
  });
});




class PageActivityMaintainer {
  constructor() {
    this.interval = 5000;
    this.activeTabs = new Map(); // 存储用户手动激活的标签页
    this.timers = new Map(); // 存储定时器
  }

  init() {

    // 监听来自popup的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.action === 'toggleActivity') {
        this.toggleTabActivity(request.tabId, request.enable);
        sendResponse({ success: true });
      }
      if (request.action === 'checkStatus') {
        sendResponse({ isActive: this.activeTabs.get(request.tabId) });
      }
      if (request.action === 'getActiveTabs') {
        sendResponse(this.getActiveTabs());
      }
      if (request.action === 'clearAllTabs') {
        this.clearAllTabs();
      }
      return true;
    });

    // 清理已关闭标签页的定时器
    chrome.tabs.onRemoved.addListener((tabId) => {
      this.clearTabTimer(tabId);
    });
  }

  // 切换标签页活跃状态
  toggleTabActivity(tabId, enable) {
    if (enable) {
      if (!this.timers.has(tabId)) {
        const timer = setInterval(() => {
          this.simulateActivity(tabId);
        }, this.interval);
        this.timers.set(tabId, timer);
        this.activeTabs.set(tabId, true);
      }
    } else {
      this.clearTabTimer(tabId);
    }
  }

  // 模拟活动
  async simulateActivity(tabId) {
    try {
      await chrome.scripting.executeScript({
        target: { tabId },
        func: () => {
          const activities = [
            () => {
              // 模拟鼠标轨迹
              const steps = 5 + Math.floor(Math.random() * 10);
              for (let i = 0; i < steps; i++) {
                setTimeout(() => {
                  window.dispatchEvent(new MouseEvent('mousemove', {
                    clientX: Math.random() * window.innerWidth,
                    clientY: Math.random() * window.innerHeight,
                    bubbles: true
                  }));
                }, i * 200);
              }
            },
            () => {
              // 自然滚动
              const distance = 100 + Math.random() * 500;
              window.scrollBy({
                top: Math.random() > 0.5 ? distance : -distance,
                behavior: 'smooth'
              });
            },
            () => document.activeElement?.blur()
          ];
          activities[Math.floor(Math.random() * activities.length)]();
        }
      });
    } catch (error) {
      console.error('Activity simulation failed:', error);
      this.clearTabTimer(tabId);
    }
  }

  // 清理定时器
  clearTabTimer(tabId) {
    if (this.timers.has(tabId)) {
      clearInterval(this.timers.get(tabId));
      this.timers.delete(tabId);
      this.activeTabs.delete(tabId);
    }
  }

  // 清除方法
  clearAllTabs() {
    this.timers.forEach((timer, tabId) => {
      clearInterval(timer);
    });
    this.timers.clear();
    this.activeTabs.clear();
  }

  // 获取活跃标签页状态
  getActiveTabs() {
    return Array.from(this.activeTabs.keys());
  }
}

const maintainer = new PageActivityMaintainer();
maintainer.init();




















